//
//  ComposeViewController.swift
//  swift_demo_weibo
//
//  Created by 杨兵 on 15/5/22.
//  Copyright (c) 2015年 bing. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController, UIScrollViewDelegate, UITextViewDelegate {

    @IBOutlet weak var sendbtn: UIBarButtonItem!
    
    @IBOutlet weak var nameLbl: UILabel!
    
    @IBOutlet weak var contentView: EmoticonsTextView!
    
    //  内容框提示按钮
    @IBOutlet weak var sharedTipLbl: UILabel!
    
    // toolbar下面的约束
    @IBOutlet weak var toolbarBottomconstraint: NSLayoutConstraint!
    
    // 图片容器的高度约束
    @IBOutlet weak var imgContainerHeightConstraint: NSLayoutConstraint!
    
    // 图片容器的控制器
    var ImageContainerContr: ImageContainerViewController?
    
    // 键盘容器视图
    @IBOutlet weak var MycontainerView: UIView!
    
    @IBAction func closeClick(sender: UIBarButtonItem) {
        self.contentView.resignFirstResponder()
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    
    @IBAction func sendClick(sender: UIBarButtonItem) {
        sendWeibo()
    }

    
    // 发送微博
    func sendWeibo() {
        SVProgressHUD.showWithStatus("发送中...")
        let params = ["access_token": userInfoShared?.access_token, "status": contentView.fullText()]
        
        // 如果有图片,就将图片上传图片
        if ImageContainerContr?.imageList.count > 0 {
            let urlstring = "https://upload.api.weibo.com/2/statuses/upload.json"
            
            // 参数字典,获取第一张图片
            let image = ImageContainerContr?.imageList[0]
            let data = UIImagePNGRepresentation(image)
            
            // 保存到服务器的文件名
            let datalist = ["service": data]
            
            // 网络访问,上传图片
            NetWorkingTools.uploadPicture(urlstring, fieldName: "pic", datalist: datalist, parameters: params, complete: { (JSON) -> () in
                println("图片微博发送结束")
                self.contentView.resignFirstResponder()
                SVProgressHUD.showSuccessWithStatus("发送成功", maskType: SVProgressHUDMaskType.Black)
                self.dismissViewControllerAnimated(true, completion: nil)
            })
            return
        }
        
        // 没有图片
        let url = "https://api.weibo.com/2/statuses/update.json"
        NetWorkingTools.requestJSON(.POST, URLString: url, parameters: params) { (JSON) -> () in
            println("发送微博结束")
            SVProgressHUD.dismiss()
            self.contentView.resignFirstResponder()
            self.dismissViewControllerAnimated(true, completion: nil)
        }
    }
    
    
    // MARK: - UITextFieldDelegate
    // 处理文字140个汉字
    let wordcount = 140
    //  监控文字改变,如果文字超过了140个字,就将文字截取
    func textViewDidChange(textView: UITextView) {
        
        // 没有文字发送按钮禁用
        self.sendbtn.enabled = count(textView.text) > 0 ? true : false
        
        // 有文字的时候,提示按钮隐藏
        self.sharedTipLbl.hidden = self.sendbtn.enabled
        
        // 检查文字字数140个,多了截取
        if count(textView.text) > wordcount {
            textView.text = (textView.text as NSString).substringToIndex(wordcount)
        }
        
    }
    

    func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {
        if count(textView.text) + count(text) > wordcount {
            return false
        }
        return true
    }
    

    
    // MARK: - UIScrollViewDelegate
    // 滚动关掉键盘
    func scrollViewDidScroll(scrollView: UIScrollView) {
        if scrollView.contentOffset.y > 0 {
            self.contentView.resignFirstResponder()
        }
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
    }
    
    func setupUI() {
        // 添加表情键盘
        addChildViewController(emoticonKeyboardVC)
        
        nameLbl.text = userInfoShared?.name
        contentView.becomeFirstResponder()
        self.sendbtn.enabled = false
        regKeybordChange()
        imgContainerHeightConstraint.constant = 0
        self.automaticallyAdjustsScrollViewInsets = false
        
        // 将子控制添加到当前控制器中
        for vc in childViewControllers {
            if vc is ImageContainerViewController {
                ImageContainerContr = vc as? ImageContainerViewController
                break
            }
        }
    }
    
    
    
    // MARK: - 键盘样式的变换
    func regKeybordChange() {
        // 键盘变化
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyChangeNotifi:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        // 键盘隐藏
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyChangeNotifi:", name: UIKeyboardWillHideNotification, object: nil)
    }
    
    
    func keyChangeNotifi(noti: NSNotification) {
        var duration = noti.userInfo![UIKeyboardAnimationDurationUserInfoKey] as? NSTimeInterval
        let constant = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue().origin.y
        
        UIView.animateWithDuration(duration! , animations: { () -> Void in
            self.toolbarBottomconstraint.constant = UIScreen.mainScreen().bounds.height - constant
            self.view.layoutIfNeeded()
        }) { (_) -> Void in
                
        }
    }
    
    
    // MARK: - 键盘内容的处理
    // 照片容器
    @IBAction func showImgContainer(sender: AnyObject) {
        // 隐藏键盘
        contentView.resignFirstResponder()
        
        let height = UIScreen.mainScreen().bounds.height / 3
        let imgHeight = imgContainerHeightConstraint.constant
        imgContainerHeightConstraint.constant = imgHeight > 0 ? 0 :height
    }
    
    
    // MARK: - 表情键盘
    @IBAction func showEmoticonContainer(sender: AnyObject) {
        // 收起图片选择容器
        imgContainerHeightConstraint.constant = 0
        UIView.setAnimationsEnabled(false)
        
        contentView.resignFirstResponder()
        // nil 是系统默认键盘
        contentView.inputView = (contentView.inputView) == nil ? emoticonKeyboardVC.view : nil
        contentView.becomeFirstResponder()
        UIView.setAnimationsEnabled(true)
    }
    
    // 选中的表情
    lazy var emoticonKeyboardVC:EmoticonInputController = {
        weak var weakself = self

        // 回调函数,选中了模型之后,将模型装换为图像写入textView中
        return EmoticonInputController(selectedModal: { (modal) -> () in
            
            weakself!.contentView.insertAttachment(modal)
        })
        
    }()
    
    
    
    
    deinit {
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

}
